//
//  ViewController.swift
//  SwiftBaseProject
//
//  Created by 苏州巨细 on 2018/5/17.
//  Copyright © 2018年 苏州巨细. All rights reserved.
//

import UIKit
//import Lottie


class ViewController: BaseViewController {
    
    var tableView: UITableView?
    
    
    
    var button: UIButton?
    
    let dataArr: [String] = ["123123","12312312313123123123123123123123123","1231231231312312312312312312312312312312312313123123123123123123123123","1231231231312312312312312312312312312312312313123123123123123123123123123123123131231231231231231231231231231231231312312312312312312312312312312312313123123123123123123123123","1231231","3453434343434","5546346346","5546346346","5546346346","5546346346"]
    
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let inch = calculateScreenInch()
        
        printLog("\(inch)")
        
//        NotificationCenter.default.addObserver(self, selector: #selector(testAPI), name: NSNotification.Name(rawValue: NotificationEnum.LoginNotification.rawValue), object: nil)
        
        
        let arr = [2,1,3,nil,"2"] as [Any?]
        
        let result = arr.compactMap() { $0 as? String }
        
        let name = "222"
        
        printLog(result)
        
//        HUDUtil.showMessage("111", withDelay: 15)
    
        
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    override func initData() {
        super.initData()
        printLog("子类初始化数据")
        testJsonToDict()
    }
    
    override func initUI() {
        super.initUI()
        
        self.title = "555"
        
//        setupCustomView()
        
//        base_changeNavigationTitleWithString("555")
//
//        base_createRightNavigationBar(title: "222")
//
//        base_createLeftNavigationBar(title: "111")
//
//        setupTableView()
//
//        setupMJRefresh()
        
//        testImageView()
        
//        testFullImagePath()
        
//        testAPI()
        
//        testHandyJson()
        
//        testLottieView()
        
        testViewExtension()
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

// MARK: - 点击事件
extension ViewController {
    
    override func base_leftNavigationButtonItemClick() {
        printLog("子类点击")
    }
    
    override func base_rightNavigationButtonItemClick() {
        printLog("子类点击右")
        navigationController?.pushViewController(SecondViewController(), animated: true)
    }
}


// MARK: - 设置界面
extension ViewController {
    
    fileprivate func setupCustomView() -> Void {
        
        button = UIButton.init(type: .custom)
        button!.setTitle("点击我", for: .normal)
        button!.backgroundColor = UIColor.colorWithHexString("#676767")
        view.addSubview(button!)
        
        
        
        //设置约束
        button!.snp.makeConstraints { (make) in
            make.left.equalTo(view).offset(30)
            make.right.equalTo(view).offset(-30)
            make.center.equalTo(view)
            make.height.equalTo(40)
        }
    }
    
    
    
    fileprivate func setupTableView(){
        
        tableView = UITableView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenW, height: kScreenH-kTabBarHeight), style: .plain)
        
        guard let tableView = tableView else {
            return
        }
        tableView.dataSource = self
        tableView.delegate = self
        tableView.emptyDataSetSource = self
        tableView.emptyDataSetDelegate = self
        tableView.estimatedRowHeight = 100
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.tableFooterView = UIView()
        
        tableView.register(UINib.init(nibName: "TextTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: "TextTableViewCell")
        view.addSubview(tableView)
        
//        tableView.snp.makeConstraints { (make) in
//            make.left.right.bottom.top.equalTo(view)
        //        }
    }
    
    
}


// MARK: - tableView相关
extension ViewController: UITableViewDataSource,UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        
//        UIAlertController.showMsgWithAlertView(showType: .ActionSheet, title: "111", message: "2222", andController: self, actionTitleArr: ["lele","2222","ok"]) { (action) in
//            printLog("\(action.title)")
//
//            HUDUtil.showError("错误信息")
//        }
        
        if let cell = tableView.cellForRow(at: indexPath) {
            cell.becomeFirstResponder()  
            let qqItem = UIMenuItem(title: "QQ", action: #selector(mqq))
            let wechatItem = UIMenuItem(title: "wechat", action: #selector(wechat))
            let menuController = UIMenuController.shared
            menuController.menuItems = [qqItem, wechatItem]
            menuController.setTargetRect(cell.frame, in: cell.superview!)
            menuController.setMenuVisible(true, animated: true)
        }
        
    }
    
    @objc func mqq() -> () {
        
    }
    
    @objc func wechat() -> () {
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "TextTableViewCell", for: indexPath) as! TextTableViewCell
        cell.nameContent = dataArr[indexPath.row]
//        cell.setNameContent(dataArr[indexPath.row])
        return cell;
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArr.count
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    /// 测试上下加载刷新
    func setupMJRefresh() -> () {
        tableView?.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            [weak self] in
            printLog("ooooooo")
            sleep(2)
            self?.tableView?.autoEndRefreshAndHideTableFooterView(currentPageIndex: &self!.pageIndex, resultListCount: 20)
        })
        
        
        tableView?.mj_footer = MJRefreshBackNormalFooter(refreshingBlock: {
            [weak self] in
            self?.tableView?.autoEndRefreshAndHideTableFooterView(currentPageIndex: &self!.pageIndex, resultListCount: 20)
        })
        
    }
    
}

// MARK: - 测试方法
extension ViewController {
    
    /// 测试字典和数组与字符串互转
    func testJsonToDict() -> () {
        let dictionary_temp = "{\"to\":\"18037517130_8\",\"body\":{\"thumbnailLocalPath\":\"\",\"thumbnailSecretKey\":\"\",\"downloadStatus\":1,\"thumbnailSizeWidth\":0,\"sizeHight\":0,\"localPath\":\"\\/Users\\/tingyuxuan\\/Library\\/Developer\\/CoreSimulator\\/Devices\\/1A6A72D7-A5E4-40C4-9128-958201FA4CF6\\/data\\/Containers\\/Data\\/Application\\/A172FCF4-CEDA-4BF8-95E1-28D68022B65B\\/Documents\\/HyphenateSDK\\/chatbuffer\\/1467694526525.png\",\"remotePath\":\"\",\"secretKey\":\"\",\"sizeWidth\":0,\"thumbnailRemotePath\":\"\",\"thumbnailDownloadStatus\":3},\"messageId\":\"14676945265360040\",\"conversationId\":\"18037517130_8\",\"timestamp\":1467694526536,\"from\":\"18501360583_167\",\"isDeliverAcked\":false,\"isRead\":true,\"chatType\":0,\"serverTime\":1467694526536,\"isReadAcked\":false,\"ext\":{\"questionId_with_Ext\":\"102\",\"body_type\":2},\"status\":1,\"direction\":0}"
        
        let dict = dictionary_temp.toDictionary()
        
        printLog("\(dict)")
        
        let jsonArr = "[\"llll\",\"666666\"]"
        
        let arr = jsonArr.toArray()
        
        printLog("\(arr)")
        
        let testArr1 = ["222",22222] as [Any]
        
        let jsonStr1 = testArr1.toJsonString()
        
        printLog("\(jsonStr1)")
        
        let testArr = ["222":"2222","333":"3333"]
        
        let jsonStr = testArr.toJsonString()
        
        printLog("\(jsonStr)")
        
    }
    
    /// 测试图片第三方使用
    func testImageView() -> () {
        let imageView = UIImageView()
        
        //http://img.zcool.cn/community/01f09e577b85450000012e7e182cf0.jpg@1280w_1l_2o_100sh.jpg
//        imageView.kf_setImage(with: URL.init(string: ""),placeImage: "tabBar_wo_sel")
        
        
        imageView.kf_setImage(with: nil, placeImage: "tabBar_wo_sel")
        
//        imageView.image = UIImage.initWithColor(UIColor.red)
        
        imageView.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
        
        view.addSubview(imageView)
        
    }
    
    func testFullImagePath() -> () {
        
       
    }
    
    /// 测试Moya接口
    @objc func testAPI() -> () {
        
        NetworkingManager.shared.requestData(target: LoginModuleHttp.login(account: "1111", password: "2222"), successClosure: { (dataJson) in
            printLog(dataJson)
            
            
        }) { (errorCode,error) in
            
        }
        
        let params = ["phone":"13245678911"]
        
        NetworkingManager.shared.requestData(target: HomeModuleHttp.homeData(params), successClosure: { (dataJson) in
            
            let model = Cat.deserialize(from: dataJson.dictionary)
            
            printLog(model?.reason)

        }) { (errorCode,error) in
            
        }

    
    }
    
    /// 测试handyJson转换模型
    func testHandyJson() -> () {
        
        let jsonString = "[{\"id\":12345,\"color\":\"black\",\"name\":\"huahuahuahuahu\"},{\"id\":12345,\"color\":\"white\",\"name\":\"huahuahuahuahu\"}]"

        if let catArr = [Cat].deserialize(from: jsonString.toArray()) {
            for cat in catArr{
                printLog(cat?.name)
            }
        }
    
        let jsonString1 = "{\"type\":\"2\",\"id\":12345,\"color\":\"black\",\"name\":\"huahuahuahuahu\",\"ani\":{\"color\":\"heise\"}}"
        
        if let zoom = Zoom.deserialize(from: jsonString1) {
            switch zoom.type{
            case .Car?:
                printLog("没问题")
            default:
                
                break;
            }
            
        }
    
        
    }
    
    /// 测试加载本地json动画
    func testLottieView() -> () {
        let animationView = AnimationView.init(name: "start")
        animationView.backgroundColor = UIColor.green
        self.view.addSubview(animationView)
        animationView.snp_makeConstraints { (make) in
            make.center.equalToSuperview()
            make.height.width.equalToSuperview()
        }
        animationView.play { (over) in
            if (over) {
                printLog("执行结束")
                animationView.removeFromSuperview()
            }
        }
    }
    
}

extension ViewController {
    
    func testViewExtension() -> () {
        let view = TestView.init()
        self.view.addSubview(view)
        view.snp_makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        view.addTouchEvent { (view) in
            printLog(".......手势点击")
        }
    }
}
